package com.umsoft.smart.framework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * 切面代理
 */
public abstract class AspectProxy  implements Proxy{

    private static  final Logger LOGGER = LoggerFactory.getLogger(AspectProxy.class);

    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result ;
        Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMehtod();
        Object[] methodParams = proxyChain.getMethodParams();
        begin();
        try{
            if(intercept(cls,method,methodParams)){
                before(cls,method,methodParams);
                result = proxyChain.doProxyChain();
                after(cls,method,methodParams,result);
            }else{
                result = proxyChain.doProxyChain();
            }

        }catch (Exception ex){
            LOGGER.error("proxy failure",ex);
            error(cls,method,methodParams,ex);
            throw ex;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            LOGGER.error("proxy failure",throwable);
            error(cls,method,methodParams,throwable);
            throw throwable;
        } finally {
            end();
        }
        return result;
    }

    public boolean intercept(Class<?> cls,Method method,Object[] params){ return true;}
    public void before(Class<?> cls,Method method,Object[] params){}
    public void after(Class<?> cls,Method method,Object[] params,Object result){}
    public void begin(){}
    public void end(){}

    public void error(Class<?> cls,Method method,Object[] params,Throwable e){ }
}
